<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="margin-top">
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="active-0" class="margin-top" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addruleFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="active"
          tab-position="left"
          class="margin-top"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addRuleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addRuleForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addRuleForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="goodsCatList"
                v-model="addRuleForm.goods_cat"
                @change="handleChange"
                :props="addProps"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item of manyTabelData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="items" v-for="(items,i) of item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item of onlyTabelData" :key="item.attr_id">
              <el-input v-model="item.attr_vals[0]"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor v-model="addRuleForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button class="margin-top" type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览弹框 -->
    <el-dialog :visible.sync="ShowDialogVisible" width="50%">
      <img width="100%" :src="dialogImageUrl" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash"; //引用lodash工具库

export default {
  name: "add",
  data() {
    return {
      active: 0, //当前标签页索引
      addRuleForm: {
        //添加商品表单项
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      addRules: {
        //添加商品校验规则
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      selectedOptions: [], //当前选中的索引项
      goodsCatList: [], //级联选择器中的商品分类数据
      addProps: {
        //级联选择器配置项
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      manyTabelData: [], //动态参数列表
      onlyTabelData: [], //静态参数列表
      uploadUrl: "https://www.liulongbin.top:8888/api/private/v1/upload", //上传图片地址
      headerObj: {
        //上传图片请求头
        Authorization: window.sessionStorage.getItem("token")
      },
      ShowDialogVisible: false, //图片预览控制弹框
      dialogImageUrl: "" //图片预览地址
    };
  },
  methods: {
    async getCategories() {
      //获取商品分类
      const { data: res } = await this.$axios.get("categories");
      this.goodsCatList = res.data;
    },
    handleChange() {
      //级联选择器商品分类发生改变事件
      if (this.addRuleForm.goods_cat.length !== 3) {
        //判断是否选择的是第三项
        this.addRuleForm.goods_cat = [];
        return;
      }
      console.log(this.addRuleForm);
    },
    beforeTabLeave(activeName, oldActiveName) {
      //标签页切换前钩子函数，判断级联选择器是否选中,activeName去往的标签页，oldActiveName即将离开的
      if (oldActiveName === "0" && this.addRuleForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    async getAttributes(attr) {
      // 获取动态/静态参数
      const { data: res } = await this.$axios.get(
        `categories/${this.CateId}/attributes`,
        {
          params: { sel: attr }
        }
      );
      res.data.forEach(element => {
        element.attr_vals =
          element.attr_vals.length !== 0 ? element.attr_vals.split(" ") : [];
      });
      if (res.meta.status === 200) {
        if (attr === "many") {
          this.manyTabelData = res.data;
        } else {
          this.onlyTabelData = res.data;
        }
      }
      console.log(res);
    },
    tabClicked() {
      //标签页选中触发事件
      if (this.active === "1") {
        //选中商品参数触发
        this.getAttributes("many");
      } else if (this.active === "2") {
        //静态属性
        this.getAttributes("only");
      }
    },
    handlePreview(file) {
      // 图片预览
      this.dialogImageUrl = file.tmp_path;
      this.ShowDialogVisible = true;
    },
    handleRemove(file) {
      // 图片移除
      const filePath = file.response.data.tmp_path; //图片临时路径
      // 根据 result.response.data.temp_path 从 addForm.pics 数组中，找到要删除那个对象的索引值
      const i = this.addRuleForm.pics.findIndex(ele => ele.pic === filePath);
      this.addRuleForm.pics.splice(i, 1);
    },
    handleSuccess(res) {
      //图片上传成功操作
      // 拼接得到一个图片信息对象
      const picInfo = { pic: res.data.tmp_path };
      // 将图片信息对象push到pic数组中
      this.addRuleForm.pics.push(picInfo);
    },
    addGoods() {
      //添加商品操作
      this.$refs.addruleFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请完善表单");
        } else {
          const form = _.cloneDeep(this.addRuleForm); //深拷贝
          form.goods_cat = form.goods_cat.join(","); //数组转成字符串
          console.log(form);
          // 处理动态参数
          this.manyTabelData.forEach(item => {
            const info = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            };
            this.addRuleForm.attrs.push(info);
          });
          // 处理静态属性
          this.onlyTabelData.forEach(item => {
            const info = { attr_id: item.attr_id, attr_value: item.attr_vals };
            this.addRuleForm.attrs.push(info);
          });
          form.attrs = this.addRuleForm.attrs;
          //发起添加商品请求
          const { data: res } = await this.$axios.post("goods", form);
          if (res.meta.status === 201) {
            this.$message.success("添加商品成功");
            this.$router.push("/goods");
          } else {
            this.$message.error("添加商品失败");
          }
        }
      });
    }
  },
  computed: {
    CateId() {
      //商品分类ID
      if (this.addRuleForm.goods_cat.length === 3) {
        return this.addRuleForm.goods_cat[
          this.addRuleForm.goods_cat.length - 1
        ];
      } else {
        return null;
      }
    }
  },
  created() {
    this.getCategories();
  }
};
</script>

<style>
.margin-top {
  margin-top: 20px;
}
.el-step__title {
  font-size: 12px !important;
}
.el-checkbox {
  margin: 0 10px 0 0;
}
.ql-editor {
  height: 500px;
}
</style>